ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this
P A H N
A P L S I I G
Y I R

题目大意:给定一个字符串,按Z形排列,按行输出排列结果,convert("PAYPALISHIRING", 3) => "PAHNAPLSIIGYIR",Z形列数是可变的。

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/4
 * 找规律的题目,当然也可以构造二维字符串
 * 周期是2 * numsRows - 1, 同一周期内,第j列下一个数为i + (numsRows * 2 - j)
 */
public class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1 || s == null) return s;

        String result = ""; // 换做字符数组会更快一些
        int len = s.length();
        int step = 2 * numRows - 2;
        for (int j = 1; j <= numRows ; j++) {
            for (int i = j; i <= len; i += step) {
                result += s.charAt(i - 1);
                if (j != 1 && j != numRows) {
                    int t = (numRows - j) * 2 + i;
                    if (t <= len) {
                        result += s.charAt(t - 1);
                    }
                }
            }
        }
        return result;
    }
}
gzdaijie            updated 2016-05-05 01:23:39

results matching ""

    No results matching ""